package com.ruoyi.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.common.Result;
import com.ruoyi.entity.DecorationRecord;
import com.ruoyi.service.DecorationRecordService;
import com.ruoyi.service.AliyunAIService;
import com.ruoyi.service.FileStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Base64;
import java.io.File;
import java.io.FileInputStream;

/**
 * 装饰记录控制器
 * 处理装饰记录相关的HTTP请求
 *
 * @author ruoyi
 */
@Slf4j
@Api(tags = "装饰记录管理接口")
@RestController
@RequestMapping("/api/decoration")
public class DecorationController {

    @Autowired
    private DecorationRecordService decorationRecordService;

    @Autowired
    private AliyunAIService aliyunAIService;

    @Autowired
    private FileStorageService fileStorageService;

    @ApiOperation("创建装饰记录")
    @PostMapping("/record")
    public Result<DecorationRecord> createRecord(@RequestBody DecorationRecord record) {
        try {
            if (record.getUserId() == null) {
                return Result.error("用户ID不能为空");
            }
            record.setCreatedAt(LocalDateTime.now());
            record.setStatus(2); // 设置状态为生成中
            decorationRecordService.createRecord(record);
            return Result.success(record);
        } catch (Exception e) {
            log.error("创建装饰记录失败", e);
            return Result.error("创建装饰记录失败：" + e.getMessage());
        }
    }

    @ApiOperation("使用文本生成图片")
    @PostMapping("/generateFromText")
    public Result<String> generateFromText(
            @ApiParam("用户ID") @RequestParam(defaultValue = "1") Integer userId,
            @ApiParam("文本描述") @RequestParam(required = false) String prompt,
            @ApiParam("房间图片URL") @RequestParam(required = false) String roomImageUrl,
            @ApiParam("房间ID") @RequestParam(required = false) Integer roomId,
            @ApiParam("文本描述") @RequestBody(required = false) Map<String, String> body) {

        DecorationRecord record = new DecorationRecord();
        try {
            // 检查用户ID
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }

            // 从请求参数或请求体中获取prompt和roomImageUrl
            String finalPrompt = prompt;
            String finalRoomImageUrl = roomImageUrl;
            Integer finalRoomId = roomId;
            
            if (body != null) {
                if (finalPrompt == null) {
                    finalPrompt = body.get("prompt");
                }
                if (finalRoomImageUrl == null) {
                    finalRoomImageUrl = body.get("roomImageUrl");
                }
                // 如果URL参数中没有roomId，尝试从body中获取
                if (finalRoomId == null && body.containsKey("roomId")) {
                    try {
                        finalRoomId = Integer.parseInt(body.get("roomId"));
                    } catch (NumberFormatException e) {
                        log.warn("无法解析roomId: {}", body.get("roomId"));
                    }
                }
            }

            if (finalPrompt == null || finalPrompt.trim().isEmpty()) {
                return Result.error("提示词不能为空");
            }

            // 1. 创建初始记录
            record.setUserId(userId);
            record.setStyleId(1); // 设置默认风格ID为1
            record.setPrompt(finalPrompt);
            if (finalRoomId != null) {
                record.setRoomId(finalRoomId);
                log.info("设置房间ID: {}", finalRoomId);
            }

            String minioUrl = null;
            // 处理房间图片
            if (finalRoomImageUrl != null && !finalRoomImageUrl.trim().isEmpty()) {
                try {
                    byte[] imageData = null;

                    // 处理base64图片数据
                    if (body != null && body.containsKey("imageData")) {
                        String base64Data = body.get("imageData");
                        if (base64Data != null && !base64Data.isEmpty()) {
                            // 移除可能存在的base64头
                            if (base64Data.contains(",")) {
                                base64Data = base64Data.split(",")[1];
                            }
                            imageData = Base64.getDecoder().decode(base64Data);
                        }
                    }
                    // 如果没有imageData，检查roomImageUrl是否为base64数据
                    else if (finalRoomImageUrl.startsWith("data:image")) {
                        String base64Data = finalRoomImageUrl.split(",")[1];
                        imageData = Base64.getDecoder().decode(base64Data);
                    }

                    if (imageData != null) {
                        // 验证图片数据
                        if (imageData.length == 0) {
                            return Result.error("图片数据为空，请重新上传");
                        }

                        // 生成文件名
                        String extension = ".png";
                        if (finalRoomImageUrl.contains(".")) {
                            extension = finalRoomImageUrl.substring(finalRoomImageUrl.lastIndexOf("."));
                        }
                        String fileName = "room_" + System.currentTimeMillis() + extension;

                        // 上传到MinIO
                        minioUrl = fileStorageService.uploadImageBytes(fileName, imageData);
                        log.info("图片已上传到MinIO，URL: {}", minioUrl);
                        finalRoomImageUrl = minioUrl;
                    }
                    // 如果是临时文件URL，也需要处理
                    else if (finalRoomImageUrl.startsWith("http://tmp/") || finalRoomImageUrl.startsWith("wxfile://")) {
                        log.info("处理临时文件URL: {}", finalRoomImageUrl);
                        // 这里可以添加处理临时文件的逻辑
                        return Result.error("暂不支持处理临时文件URL，请提供图片数据");
                    }

                    // 设置房间图片URL
                    record.setCustomRoomUrl(finalRoomImageUrl);
                    log.info("最终使用的房间图片URL: {}", finalRoomImageUrl);
                } catch (Exception e) {
                    log.error("处理房间图片失败", e);
                    return Result.error("处理房间图片失败：" + e.getMessage());
                }
            }

            record.setCreatedAt(LocalDateTime.now());
            record.setStatus(2); // 设置状态为生成中
            decorationRecordService.createRecord(record);

            // 2. 生成图片
            String imageUrl = aliyunAIService.generateImageFromText(finalPrompt, finalRoomImageUrl);

            // 3. 更新记录状态
            record.setResultImageUrl(imageUrl);
            record.setStatus(1); // 设置状态为成功
            record.setUpdatedAt(LocalDateTime.now());
            decorationRecordService.updateRecord(record);

            return Result.success(imageUrl);
        } catch (Exception e) {
            log.error("图片生成失败", e);
            // 更新记录状态为失败
            if (record.getId() != null) {
                record.setStatus(0); // 设置状态为失败
                record.setErrorMessage(e.getMessage());
                record.setUpdatedAt(LocalDateTime.now());
                decorationRecordService.updateRecord(record);
            }
            return Result.error("图片生成失败：" + e.getMessage());
        }
    }

    @ApiOperation("获取装饰记录列表")
    @GetMapping("/record")
    public Result<IPage<DecorationRecord>> getRecords(
            @ApiParam("用户ID") @RequestParam Integer userId,
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }
            IPage<DecorationRecord> records = decorationRecordService.getUserRecords(userId, pageNum, pageSize);
            return Result.success(records);
        } catch (Exception e) {
            log.error("获取装饰记录列表失败", e);
            return Result.error("获取装饰记录列表失败：" + e.getMessage());
        }
    }

    @ApiOperation("获取装饰记录详情")
    @GetMapping("/record/{id}")
    public Result<DecorationRecord> getRecord(@PathVariable Integer id) {
        try {
            DecorationRecord record = decorationRecordService.getRecordById(id);
            if (record == null) {
                return Result.error("记录不存在");
            }
            return Result.success(record);
        } catch (Exception e) {
            log.error("获取装饰记录详情失败", e);
            return Result.error("获取装饰记录详情失败：" + e.getMessage());
        }
    }

    @ApiOperation("更新装饰记录")
    @PutMapping("/record/{id}")
    public Result<DecorationRecord> updateRecord(
            @PathVariable Integer id,
            @RequestBody DecorationRecord record) {
        try {
            record.setId(id);
            record.setUpdatedAt(LocalDateTime.now());
            decorationRecordService.updateRecord(record);
            return Result.success(record);
        } catch (Exception e) {
            log.error("更新装饰记录失败", e);
            return Result.error("更新装饰记录失败：" + e.getMessage());
        }
    }

    @ApiOperation("删除装饰记录")
    @DeleteMapping("/record/{id}")
    public Result<Void> deleteRecord(@PathVariable Integer id) {
        try {
            decorationRecordService.deleteRecord(id);
            return Result.success();
        } catch (Exception e) {
            log.error("删除装饰记录失败", e);
            return Result.error("删除装饰记录失败：" + e.getMessage());
        }
    }

    @ApiOperation("生成装饰画预览图")
    @PostMapping("/preview")
    public Result<String> generatePreview(@ApiParam("装饰画记录信息") @RequestBody DecorationRecord record) {
        try {
            // 确保记录ID不为空
            if (record.getId() == null) {
                return Result.error("记录ID不能为空");
            }

            // 从数据库获取完整的记录信息
            DecorationRecord existingRecord = decorationRecordService.getRecordById(record.getId());
            if (existingRecord == null) {
                return Result.error("记录不存在");
            }

            // 生成预览图
            String previewUrl = decorationRecordService.generatePreview(existingRecord);
            return Result.success(previewUrl);
        } catch (Exception e) {
            log.error("生成预览图失败", e);
            return Result.error(e.getMessage());
        }
    }

    @ApiOperation("上传图片并使用AI生成新图片")
    @PostMapping("/generateFromImage")
    public Result<String> generateFromImage(
            @ApiParam("用户ID") @RequestParam Integer userId,
            @ApiParam("原始图片") @RequestParam("file") MultipartFile file,
            @ApiParam("提示词") @RequestParam(value = "prompt", required = false) String prompt) {
        try {
            // 检查用户ID
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }

            // 1. 生成图片
            String imageUrl = aliyunAIService.generateImageFromImage(file, prompt);

            // 2. 创建装饰记录
            DecorationRecord record = new DecorationRecord();
            record.setUserId(userId);
            record.setCustomRoomUrl(file.getOriginalFilename());
            record.setResultImageUrl(imageUrl);
            record.setPrompt(prompt);
            record.setCreatedAt(LocalDateTime.now());
            record.setStatus(1); // 设置状态为成功
            decorationRecordService.createRecord(record);

            return Result.success(imageUrl);
        } catch (Exception e) {
            log.error("图片生成失败", e);
            return Result.error("图片生成失败：" + e.getMessage());
        }
    }
}
